<template>
  <div>
    <!-- <PackBack></PackBack> -->
    <div class="shoplist" style="margin-bottom: 100px">
      <div v-if="shopCar?.length > 0">
        <van-checkbox-group v-model="checked" ref="checkboxGroup">
          <div class="shop" v-for="item in shopCar" :key="item.id">
            <div style="display: flex; width: 100%" class="shop-left pts pbw">
              <div style="display: flex; align-items: center" class="pls">
                <van-checkbox :name="item.id" @click="methods.changeCheck">
                </van-checkbox>
              </div>
              <div class="imgs pls">
                <img
                  :src="item.photo"
                  class="shop-img"
                  width="90"
                  height="90"
                  style="border-radius: 5px"
                  alt=""
                />
              </div>

              <div class="shop-right prs" style="flex: 1; margin-left: 10px">
                <div>
                  <!-- 0 -->
                  <div class="myflex">
                    <p class="weight" style="font-size: 14px">
                      {{ item.name }}
                    </p>
                    <div>
                      <van-tag type="warning"
                        >库存: {{ item.inventory }}</van-tag
                      >
                    </div>
                  </div>

                  <!-- 1 -->
                  <div class="myflex" style="width: 100%">
                    <div>
                      <p class="font_x hui">
                        {{ item.specs }}
                        <span class="mlw">生产日期:{{ item.birthday }}</span>
                        <span class="mlw"> 保质期:{{ item.expiryday }}</span>
                      </p>
                    </div>
                  </div>
                  <!-- 2 -->
                  <div>
                    <van-tag type="primary">{{ item.supplier }}</van-tag>
                  </div>
                  <!-- 3 -->
                  <div class="myflex" style="width: 100%">
                    <!-- <div>
                      <van-tag type="danger">销量:{{ item.sales }}</van-tag>
                    </div> -->
                    <div>
                      <p class="font_x hui">
                        剩余库存:{{ item.inventory - item.sales }}
                      </p>
                    </div>
                  </div>
                  <!-- 4 -->
                  <div class="myflex" style="width: 100%">
                    <div>
                      <p
                        v-if="item.isPromote === 0"
                        class="red weight"
                        style="font-size: 14px"
                      >
                        ￥{{ item.price }}
                      </p>
                      <p
                        v-if="item.isPromote === 1"
                        class="red weight"
                        style="font-size: 14px"
                      >
                        ￥{{ item.promotePrice }}
                        <van-tag type="warning">促销</van-tag>
                      </p>
                    </div>
                    <div>
                      <div
                        style="display: flex"
                        v-if="
                          item.carCount !== 0 && item.inventory - item.sales > 0
                        "
                      >
                        <div
                          class="iconfont icon-jian1 number"
                          @click="methods.minusGoodCar(item)"
                        ></div>
                        <div
                          class="discount-number plw prw"
                          style="font-size: 16px; padding-top: 2px"
                        >
                          {{ item.carCount }}
                        </div>
                        <div
                          class="iconfont icon-jia number"
                          @click="methods.addGoodCar(item)"
                        ></div>
                      </div>

                      <div
                        v-if="
                          item.carCount === 0 && item.inventory - item.sales > 0
                        "
                      >
                        <div
                          class="iconfont icon-jia number"
                          @click="methods.addGoodCar(item)"
                        ></div>
                      </div>

                      <div v-if="item.inventory - item.sales <= 0">
                        <van-tag>已售罄</van-tag>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!-- <div style="height: 5px; background: rgb(241, 241, 241)"></div> -->
          </div>
        </van-checkbox-group>

        <van-submit-bar
          :price="likeShop.price * 100"
          decimal-length="2"
          button-text="提交订单"
          @submit="methods.onSubmit"
        >
          <van-checkbox @click="methods.myCheck" v-model="data.checkAll">
            全选
          </van-checkbox>
        </van-submit-bar>
      </div>

      <div v-if="shopCar?.length <= 0">
        <van-empty
          image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png"
          image-size="80"
          description="购物车为空"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { GenerateOrder } from "@/api/good";
import router from "@/router";
import { load } from "@/utils/load";
import { showToast } from "vant";
import PackBack from '@/components/PageBack.vue'
import { nextTick, onMounted, reactive, ref, watchEffect,provide } from "vue";
const parentMessage = '购物车'; // 父组件数据
provide('mytitle', parentMessage); // 提供数据给子组件
const data = reactive({
  checkAll: false,
});
const shopCar = ref([]); //购物车里的所有商品
const checkStatus = ref(false);
const likeShop = ref({
  price: 0,
  count: 0,
}); //购物车总数量和价格
const checked = ref([]);
const checkboxGroup = ref(null);

const methods = {
  /**
   * 减数量 配合watchEffect监听数据
   */
  minusGoodCar:(item)=>{
    shopCar.value.map((d) => {
      if (d.id === item.id) {
        if (d.carCount >= 1) {
          d.carCount--;
        }
      }
    });

   //将数量为0的清除出购物车
   shopCar.value=shopCar.value.filter(d=>d.carCount!==0)
    
    //更新当前选中的商品的价格
    methods.setLikeShop(shopCar);
    //更新数据
    methods.renew(shopCar);
  },
  /**
   * 配合watchEffect监听数据
   */
  addGoodCar:(item)=>{
    shopCar.value.map((d) => {
      if (d.id === item.id) {
          d.carCount++;
      }
    });
    methods.setLikeShop(shopCar);
    methods.renew(shopCar);
  },
  //更新购物车数据
  renew: (shopCar) => {
    const data= JSON.stringify(shopCar.value)
    localStorage.setItem("shopCar",data);
    const car=localStorage.getItem("shopCar");
    shopCar.value = JSON.parse(car);
  },
  //设置总金额和总数量
  setLikeShop: (shopCar) => {
    likeShop.value.price = 0;
    likeShop.value.count = 0;
    shopCar.value?.map((d) => {
      if (checked.value.includes(d.id)) {
        if (d.isPromote === 1) {
          likeShop.value.price += d.promotePrice * d.carCount;
        }

        if (d.isPromote === 0) {
          likeShop.value.price += d.price * d.carCount;
        }
        likeShop.value.count += d.carCount;
      }
    });

  },
  //商品复选框联动购物车
  changeCheck: () => {
    methods.setLikeShop(shopCar);
    if (checked.value.length >= shopCar.value.length) {
      data.checkAll = true;
    } else {
      data.checkAll = false;
    }
  },
  //判断是否全部选中
  myCheck: () => {
    if (!checkStatus.value) {
      methods.checkAll();
      checkStatus.value = true;
     
    } else {
      methods.toggleAll();
      checkStatus.value = false;
    }
  },
  //选中所有
  checkAll: () => {
    
    checkboxGroup.value.toggleAll(true);
    methods.setLikeShop(shopCar);
  },
  //取消选中所有
  toggleAll: () => {
    checkboxGroup.value.toggleAll();
    methods.setLikeShop([]);
  },
  //提交订单
  onSubmit: async () => {
    if (likeShop.value.count <= 0) {
      showToast("请选择商品");
      return;
    }
    const orders = shopCar.value.map((d) => {
      if (checked.value.includes(d.id)) {
        return {
          gid: d.id,
          number: d.carCount,
        };
      }
    });
    //过滤勾中的订单
    const arr = orders.filter((d) => d != undefined);

    if (orders.length <= 0) {
      showToast("请选择商品");
      return;
    }
    console.log(likeShop.value.price);
    load();
    
    const res = await GenerateOrder({
      orders: arr,
      number: null,
      money: likeShop.value.price,
    });

    if (res.result === 0) {
      showToast("下单成功");
      // localStorage.setItem("shopCar", []);
     
     const arr= shopCar.value.map((d, i) => {
        if (checked.value.includes(d.id)) {
         return d=0
        }else{
          return d
        }
      });
     
      shopCar.value=arr.filter((d)=> d !== 0);
      likeShop.value.price=0;
      methods.renew(shopCar);

     setTimeout(()=>{
      router.push("/order")
     },1000)
    } else {
      showToast(res.message);
    }
  },
};

onMounted(() => {
  const shopCar_history = localStorage.getItem("shopCar");
  //符合条件即为不需要初始化购物车
  if (
    shopCar_history !== "" &&
    shopCar_history !== null &&
    shopCar_history !== undefined
  ) {
    //不需要初始化购物车，将历史购物车赋值当前页面
    //缓存中的购物车
    const cars = JSON.parse(shopCar_history);
    //本页面显示数据赋值
    shopCar.value = cars;

  } else {
    //初始化购物车
    localStorage.setItem("shopCar", JSON.stringify([]));
  }
});

watchEffect(() => {
  shopCar;
});
</script>

<style  scoped>
.shop {
  margin: 10px;
  border: 1px solid #ebedf0;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}
.number {
  color: red;
  font-size: 22px;
}

.historys div {
  margin-left: 10px;
  /* float: left; */
  padding: 0px 8px 0px 8px;
  text-align: center;
  background: #efefef;
  border-radius: 14px;
  height: 30px;
  min-width: 30px;
  line-height: 30px;
  color: #fd9c74;
  font-weight: 500;
  font-size: 14px;
}

.historys {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebedf0;
}

p {
  margin: 3px;
}
</style>